<template>
  <view class="add_rule_container">
    <nav-bar
      :title="edit ? '修改宝贝' : '发布宝贝'"
      left-icon="back"
      custom-class="vantabar"
      z-index="9999"
      :fixed="true"
      :statusBar="true"
      @clickLeft="onClickLeft"
    >
      <van-button
        slot="right"
        v-if="show_add"
        @tap="submit"
        custom-class="product_btn"
        >发布</van-button
      >
    </nav-bar>
    <view class="show_add" v-show="show_add">
      <van-field
        :value="param.goods.goods_title"
        placeholder="给宝贝起个名字"
        :border="false"
        @change="change_goods_name"
        :maxlength="20"
        label="宝贝标题"
        required
        :input-class="check_param['goods_title'].check ? 'red_border' : ''"
      />
      <van-field
        :value="param.goods.goods_short_desc"
        placeholder="请输入宝贝卖点"
        :border="false"
        @change="change_goods_sellingpoint"
        label="宝贝卖点"
        required
        :input-class="check_param['goods_short_desc'].check ? 'red_border' : ''"
      />
      <view
        class="start_pick_container"
        @tap="choose_cate"
        style="margin-bottom: 10rpx"
      >
        <van-field :border="false" label="分类" disabled required />
        <view
          v-if="!cate_name"
          :class="[
            'placeholder',
            check_param['cate_id'].check ? 'red_border' : '',
          ]"
          >请选择分类</view
        >
        <view v-if="cate_name" class="placeholder">{{ cate_name }}</view>
      </view>
      <view style="display: flex; align-items: center">
        <van-field
          :border="false"
          label="用于"
          required
          input-class="none_input"
          label-class="forsrc_label"
        />
        <checkbox-group
          name="for_src"
          @change="checkboxChange"
          style="margin-left: 0rpx"
          :class="[
            'checkbox-group',
            check_param['for_src'].check ? 'red_border' : '',
          ]"
        >
          <label v-for="(item, i) in for_src" :key="item.value">
            <checkbox :value="item.value" :checked="item.checked" />
            {{ item.name }}
          </label>
        </checkbox-group>
      </view>
      <van-field
        :value="param.goods.commission_rate"
        placeholder="(如: 25 => 即 表示佣金率 25%)"
        :border="false"
        @change="change_commission_rate"
        :input-class="check_param['commission_rate'].check ? 'red_border' : ''"
        type="number"
        label="佣金率%"
        required
      />
      <!-- <van-cell>
        <view slot="title">{{
          param.goods.gift_mode == 1 ? "支持礼券" : "不支持礼券"
        }}</view>
        <view slot="">
          <van-switch
            :checked="param.goods.gift_mode == 1 ? true : false"
            @change="change_gift_mode"
          />
        </view>
      </van-cell> -->
      <view style="padding-left: 30upx; border-top: 20rpx solid #f4f0fe"
        >宝贝封面</view
      >
      <view style="padding-left: 30upx; color: #969799"
        >宝贝图片大小不超过500k,1000*1000以内</view
      >
      <view
        class="upload"
        style="padding-left: 20upx; border-bottom: 20rpx solid #f4f0fe"
      >
        <uImg
          ref="upimg"
          :canUploadFile="true"
          :limit="limit"
          :uploadFileUrl="uploadFileUrl"
          :uImgList.sync="uImgList"
          @uploadSuccess="uploadSuccess"
          :fileKeyName="name"
          @delete="delete_img"
          :class="check_param['cover_image'].check ? 'red_border_up' : ''"
        />
      </view>
      <van-field
        placeholder="例如：尺寸,颜色"
        v-model="spec_title.spec1_title"
        :border="false"
        @change="change_spec1_title"
        :maxlength="20"
        label="规格一标题"
        required
      />
      <van-field
        placeholder="例如：尺寸,颜色"
        :border="false"
        v-model="spec_title.spec2_title"
        @change="change_spec2_title"
        :maxlength="20"
        label="规格二标题"
        required
      />
      <van-cell >
        <view slot="title">宝贝规格</view>
        <view slot="">
          <van-button size="mini" @tap="add_spec" custom-class="add_btn" style="margin-right:30rpx !important"
            >新增</van-button
          >
        </view>
      </van-cell>
      <van-cell
        v-if="param.spec_detail == null || param.spec_detail.length == 0"
      >
        <view slot="title">还未添加规格,请点新增</view>
      </van-cell>
      <view
        class="spec_container"
        v-if="param.spec_detail != null && param.spec_detail.length > 0"
      >
        <van-cell
          v-for="(item, index) in param.spec_detail"
          :key="index"
          title-class="cell_title"
          value-class="cell_value"
        >
          <view slot="title" style="display: flex">
            <view class="aa">规格{{ index + 1 }}</view>
            <view class="spec_detail" style="margin-left: 10rpx"
              >{{ param.spec_detail[index].spec1 }}/{{
                param.spec_detail[index].spec2
              }}</view
            >
          </view>
          <view slot="" class="">
            <van-button
              size="mini"
              type="danger"
              @tap="check_spec(index, 'check')"
              custom-class="check_btn"
              >查看规格</van-button
            >
          </view>
        </van-cell>
      </view>
      <view
        class="nav_container"
        :style="menufixed ? 'top:' + statusHeight + 'px;position:fixed' : ''"
      >
        <view class="divide"></view>
        <van-cell custom-class="detai_">
          <view slot="title">宝贝详情<text style="color:red">(可使用下方编辑栏上传图片)</text></view>
        </van-cell>
      </view>

      <jinEdit
        placeholder="请输入内容"
        @editOk="editOk"
        :uploadFileUrl="uploadFileUrl"
        @input="edit_input"
        :html="param.goods.goods_detail"
      ></jinEdit>
      <!-- <view class="btn_box">
        <van-button @tap="submit" size="large" color="#f95a4b">发布</van-button>
      </view> -->
    </view>
    <w-picker
      :visible.sync="show_cate_picker"
      mode="selector"
      value="美妆护肤"
      default-type="label"
      :options="cate_list"
      @confirm="onConfirm_cate($event, 'selector')"
      @cancel="onCancel_cate"
      ref="selector"
    ></w-picker>
    <van-toast id="van-toast" />
  </view>
</template>

<script>
import Vue from "vue";
import app from "@/App.vue";
import jinEdit from "../../components/jin-edit/jin-edit.vue";
import uImg from "../../components/zhtx-uploadImg/zhtx-uploadImg";
import wPicker from "@/components/w-picker/w-picker.vue";
import { save_good, get_cate, query_one } from "../../utils/imapi";
export default {
  props: {},
  components: { uImg, wPicker, jinEdit },
  data() {
    return {
      show_cate: true,
      mch_for_src: [
        {
          name: "商城",
          value: "1",
        },
        {
          name: "砍价霸王餐",
          value: "3",
        },
      ],
      for_src: [
        {
          name: "商城",
          value: "1",
        },
        {
          name: "砍价免费拿升级版",
          value: "2",
        },
        {
          name: "砍价霸王餐",
          value: "3",
        },
        {
          name: "砍价推客版",
          value: "4",
        },
        {
          name: "直播间",
          value: "8",
        },
      ],
      goods_cate: {
        1: "美妆护肤",
        2: "时尚穿搭",
        3: "母婴萌娃",
        4: "美食美味",
        5: "日用百货",
        6: "珠宝文玩",
        7: "知识教育",
        8: "爱心公益",
      },
      param: {
        goods: {
          gift_mode: 0,
          cate_id: "",
          goods_title: "",
          commission_rate: "",
          cover_image: "",
          goods_title: "",
          goods_available_amt: "",
          goods_total_amt: "",
          for_src: "",
          small_images: "",
          goods_short_desc: "",
          goods_detail:''
        },
        spec_detail: [],
        spec_title: {},
      },
      cate_name: "",
      uImgList: [],
      uImgList1: [],
      uploadFileUrl:
        "https://api.comm.t.xingkonglian.net:8098/api/v1/oss/upload_starx",
      name: "file",
      countdown: "",
      limit: 5,
      limit1: 1,
      cate_list: [],
      show_cate_picker: false,
      show_cate_picker2: false,
      imgList: [],
      imgList1: [],
      show_add: true,
      spec: {
        spec1: "",
        spec2: "",
        market_price: "",
        platform_price: "",
        amount: "",
        img_url: "",
      }, // 规格参数
      spec_title: {
        spec1_title: "",
        spec2_title: "",
      },
      check: false,
      check_index: 0,
      edit: false,
      menuTop: 0,
      statusHeight: 0,
      menufixed: false,
      nav_container_height: 0,
      can_submit: true,
      userinfo: "",
      check_param: {
        goods_title: {
          check: false,
          msg: "请输入宝贝标题",
        },
        goods_short_desc: {
          check: false,
          msg: "请输入宝贝卖点",
        },
        cate_id: {
          check: false,
          msg: "请选择宝贝分类",
        },
        for_src: {
          check: false,
          msg: "请选择宝贝用于何处",
        },
        commission_rate: {
          check: false,
          msg: "请输入宝贝佣金率",
        },
        cover_image: {
          check: false,
          msg: "请至少上传一张宝贝封面",
        },
      },
    };
  },
  computed: {},
  watch: {},
  async onLoad(options) {
    if (JSON.stringify(app.globalData.userinfo) != "{}") {
      this.userinfo = app.globalData.userinfo;
    } else {
      this.userinfo = uni.getStorageSync("userinfo");
    }

    if (this.userinfo.org_type == "1") {
      this.for_src = this.mch_for_src;
    }

    if (options.item) {
      this.param = JSON.parse(options.item);
      this.param.id = JSON.parse(options.item).goods.id;
      console.log(this.param);
      this.for_src = JSON.parse(this.param.goods.for_src);
      console.log(this.for_src);
      // this.param.goods.for_src = 
      const arr = []
      this.for_src.forEach(item=>{
        arr.push(item.value)
      })
       this.param.goods.for_src =arr.join(',')
       console.log(this.param.goods.for_src);
      // this.$set(this.param.goods,'goods_title','111')
      if (this.param.goods.small_images != "") {
        this.uImgList = this.imgList = this.param.goods.small_images.split(",");
      }
      this.cate_name = this.goods_cate[this.param.goods.cate_id];
      this.spec_title.spec1_title = this.param.spec_title.spec1_title;
      this.spec_title.spec2_title = this.param.spec_title.spec2_title;
      this.check_index = options.index;
      this.edit = true;
    }

    this.get_cate();
  },
  onReady() {
    console.log(app);
    const query1 = uni.createSelectorQuery();
    query1.select(".nav_container").boundingClientRect();
    query1.exec((res) => {
      console.log(res);
      this.nav_container_height = res.height;
      this.menuTop = res[0].top - app.globalData.StatusBar;
    });
    this.statusHeight = app.globalData.StatusBar + 44;
  },
  onShow() {},
  methods: {
    checkboxChange(e) {
      if (e.detail.value && this.check_param["for_src"].check) {
        this.check_param["for_src"].check = false;
      }
      var items = this.for_src,
        values = e.detail.value;
      this.param.goods.for_src = values.join(",");
      for (var i = 0, lenI = items.length; i < lenI; ++i) {
        const item = items[i];
        if (values.includes(item.value)) {
          this.$set(item, "checked", true);
        } else {
          this.$set(item, "checked", false);
        }
      }
    },
    edit_input(e) {
      console.log(e);
      this.param.goods.goods_detail=e.detail.html
    },
    choose_cate() {
      this.show_cate_picker = true;
    },
    onCancel_cate() {
      this.show_cate_picker = false;
    },
    onConfirm_cate(e, f) {
      console.log(e, f);
      this.cate_name = e.result;
      this.param.goods.cate_id = e.value;
      this.show_cate_picker = false;
      if (!this.param.goods.cate_id && this.check_param["cate_id"].check) {
        this.check_param["cate_id"].check = false;
      }
      console.log(this.param);
    },
    change_gift_mode(e) {
      console.log(e);
      this.param.goods.gift_mode = e.detail ? 1 : 0;
    },
    uploadSuccess(result) {
      if (result.statusCode == 200) {
         this.check_param["cover_image"].check = false;
        //上传成功的回调处理
        console.log(result.data);
        const img = JSON.parse(result.data).data;
        console.log(img);
        console.log(this.imgList);
        if (this.edit) {
          this.imgList.pop();
          this.imgList.push(img);
          this.param.goods.cover_image = this.imgList[0];
        } else {
          this.imgList.push(img);
          this.param.goods.cover_image = this.imgList[0];
        }
      } else {
      }
    },
    delete_img(index) {
      console.log(index);
      console.log(this.imgList);
      this.imgList.splice(index, 1);
      // console.log(this.imgList);
    },
    uploadSuccess1(result) {
      if (result.statusCode == 200) {
        //上传成功的回调处理
        console.log(result.data);
        const img = JSON.parse(result.data).data;
        console.log(img);
        this.imgList1.push(img);
        this.spec.img_url = this.imgList1[0];
      } else {
      }
    },
    delete_img1(index) {
      console.log(index);
      this.imgList1.splice(index, 1);
      console.log(this.imgList1);
    },
    change_goods_name(e) {
      if (e.detail && this.check_param["goods_title"].check) {
        this.check_param["goods_title"].check = false;
      }
      this.param.goods.goods_title = e.detail;
    },
    change_goods_sellingpoint(e) {
      if (e.detail && this.check_param["goods_short_desc"].check) {
        this.check_param["goods_short_desc"].check = false;
      }
      this.param.goods.goods_short_desc = e.detail;
    },
    change_commission_rate(e) {
      if (e.detail && this.check_param["commission_rate"].check) {
        this.check_param["commission_rate"].check = false;
      }
      this.param.goods.commission_rate = e.detail;
    },
    change_spec1_title(e) {
      console.log(e);
      this.spec_title.spec1_title = e.detail;
    },
    change_spec1_content(e) {
      this.$set(this.spec, "spec1");
      this.spec.spec1 = e;
      console.log(this.spec.spec1);
    },
    change_spec2_title(e) {
      console.log(e);
      this.spec_title.spec2_title = e.detail;
    },
    change_spec2_content(e) {
      this.spec.spec2 = e;
    },
    change_prcie(e) {
      this.spec.market_price = e;
    },
    change_zk_price(e) {
      this.spec.platform_price = e;
    },
    change_ava_amount(e) {
      this.spec.amount = e;
    },
    async get_cate() {
      try {
        const data = await get_cate({
          pid: 0,
        });
        console.log(data);
        if (data.code == 0) {
          data.data.forEach((item) => {
            this.cate_list.push({ label: item.name, value: item.id });
          });
          console.log(this.cate_list);
        }
      } catch (error) {}
    },

    // 新增规格
    add_spec() {
      if (
        this.spec_title.spec1_title == "" ||
        this.spec_title.spec2_title == ""
      ) {
        return this.$toast("请输入两个规格标题");
      }
      console.log(this.param.spec_detail);
      const spec_title = JSON.stringify(this.spec_title);
      uni.navigateTo({
        url: "/pages/save_spec/save_spec?spec_title=" + spec_title,
      });
    },
    // 查看修改已创建的规格
    check_spec(index) {
      const spec = JSON.stringify(this.param.spec_detail[index]);
      const spec_title = JSON.stringify(this.spec_title);
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      });
      console.log(this.param.spec_detail[index]);
      uni.navigateTo({
        url:
          "/pages/save_spec/save_spec?check=true&index=" +
          index +
          "&spec=" +
          spec +
          "&image=" +
          this.param.spec_detail[index].img_url +
          "&spec_title=" +
          spec_title,
      });
    },
    check_param_f(which) {
      this.can_submit = true;
      this.check_param[which].check = true;
      uni.showToast({
        title: this.check_param[which].msg,
        duration: 2000,
        icon: "none",
      });
    },
    // 发布产品
    async submit() {
      if (this.can_submit) {
        this.can_submit = false;
        const timestamp = Date.parse(new Date()).toString();
        this.param.goods.cover_image =
          this.imgList.length > 1
            ? this.imgList[0] + "?" + timestamp
            : this.imgList[0] + "?" + timestamp;
        this.param.goods.small_images =
          this.imgList.length > 1 ? this.imgList.join(",") : this.imgList[0];
        console.log(this.param);
        console.log(this.param.goods.goods_short_desc);
        if (!this.param.goods.goods_title.trim()) {
          return this.check_param_f("goods_title");
        } else if (!this.param.goods.goods_short_desc.trim()) {
          return this.check_param_f("goods_short_desc");
        } else if (!this.param.goods.cate_id.trim()) {
          return this.check_param_f("cate_id");
        } else if (!this.param.goods.for_src.trim()) {
          return this.check_param_f("for_src");
        } else if (!this.param.goods.commission_rate) {
          return this.check_param_f("commission_rate");
        } else if (!this.param.goods.cover_image.trim()||this.param.goods.cover_image.indexOf('undefined')!=-1) {
          return this.check_param_f("cover_image");
        }

        // if (
        //   this.param.goods.cate_id == "" ||
        //   this.param.goods.goods_title == "" ||
        //   this.param.goods.commission_rate == "" ||
        //   this.param.goods.cover_image == ""
        // ) {
        //   this.can_submit=true
        //   return this.$toast("请输入完整数据");
        // }
        // if (this.param.spec_detail.length == 0) {
        //   this.can_submit=true
        //   return this.$toast("至少增加一种宝贝规格");
        // }

        this.param.goods.commission_rate = Number(
          this.param.goods.commission_rate
        );
        this.param.spec_title.spec1_title = this.spec_title.spec1_title;
        this.param.spec_title.spec2_title = this.spec_title.spec2_title;
        this.param.goods.goods_available_amt = this.param.goods.goods_total_amt = this.param.spec_detail.reduce(
          (res, cur) => (res += Number(cur.amount)),
          0
        );
        console.log(this.param);
        if (this.param.spec_detail.length == 0) {
          this.can_submit = true;
          return this.$toast("至少增加一种宝贝规格");
        }
        try {
          const data = await save_good(this.param);
          console.log(data);
          if (data.code == 0) {
            if (this.edit) {
              this.param.goods.commission_rate =
                this.param.goods.commission_rate / 100;
              let currentPages = getCurrentPages();
              let prepages = currentPages[currentPages.length - 2];
              prepages.$vm.$set(
                prepages.$vm.goodList,
                this.check_index,
                this.param
              );
              // prepages.goodList[this.check_index] = this.param
              prepages.$vm.$forceUpdate();
              uni.showToast({
                title: "修改成功",
                duration: 2000,
                icon: "none",
              });
            } else {
              uni.showToast({
                title: "发布成功",
                duration: 2000,
                icon: "none",
              });
            }
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1000);
          }
          setTimeout(() => {
            this.can_submit = true;
          }, 1000);
        } catch (error) {
          setTimeout(() => {
            this.can_submit = true;
          }, 1000);
        }
      }
    },
    editOk(e) {
      console.log(e);
      this.param.goods.goods_detail = e.html;
      this.$toast("保存详情成功");
    },
    onClickLeft() {
      uni.navigateBack({
        delta: 1,
      });
    },
  },
  onPageScroll: function (e) {
    if (e.scrollTop > this.menuTop - 44) {
      if (this.menufixed) return;
      this.menufixed = true;
    } else {
      if (!this.menufixed) return;
      this.menufixed = false;
    }
  },
  onReachBottom() {},
  onHide() {},
};
</script>

<style scoped lang="scss" scoped>
.start_pick_container {
  display: flex;
  align-items: center;
  position: relative;
  .placeholder {
    width: 480rpx;
    height: 60rpx;
    line-height: 60rpx;
    position: absolute;
    top: 50%;
    left: 105px;
    transform: translateY(-50%);
    color: #333333;
    text-align: left;
  }
}
.cate_picker {
  position: fixed;
  z-index: 99;
  left: 0;
  right: 0;
  bottom: 0;
}
/deep/ .txt-r {
  text-align: left !important;
  padding-left: 30upx !important;
  margin-right: 0 !important;
}
.btn_box {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 100upx;
}
.show_add {
  padding-bottom: 100upx;
  // margin-top: 100upx;
}
/deep/ .van-nav-bar {
  position: fixed;
  width: 100%;
  left: 0;
  top: 0;
}
.nav_container {
  z-index: 999;
  width: 100%;
}
// .vantabar {
//   padding-top: 20px;
// }
/deep/ .cell_value,
.cell_title {
  flex: unset !important;
}
/deep/ .product_btn,
/deep/.add_btn {
  width: 120rpx;
  height: 60rpx;
  padding: 0 !important;
  font-size: 24rpx;
  color: #fff;
  text-align: center;
  border-radius: 26rpx;
  background-color: #fe3772;
  line-height: 60rpx;
 
}
/deep/.add_btn ,/deep/.check_btn{
  margin-right: 30rpx;
}

/deep/ .detai_ {
  border-top: 20rpx solid #f4f0fe !important;
}
// .divide {
//   width: 100%;
//   height: 20rpx;
//   background-color: #F4F0FE;
// }
/deep/ .none_input {
  display: none !important;
}
/deep/ .red_border {
  width: 480rpx;
  border: 1px solid red;
}
/deep/ .red_border_up {
  // width: 200rpx;
  border: 1px solid red;
}
/deep/ .checkbox-group {
  width: 480rpx;
  padding: 10rpx 10rpx;
  overflow: unset !important;
}
/deep/ .van-cell {
  padding: 10px 0 10px 16px !important;
}
</style>
